package com.sobey.web.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.core.MongoTemplate;

import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.ServerAddress;
import com.mongodb.WriteConcern;

@Configuration
@PropertySource({"classpath:/config/properites/mongodb.properties"})
public class MongoConfig extends AbstractMongoConfiguration {
	
	@Value("${mongo.host}")
	String host;
	
	@Value("${mongo.port}")
	int port;
	
	@Value("${mongo.connectionsPerHost}")
	int connectionsPerHost;
	
	@Value("${mongo.threadsAllowedToBlockForConnectionMultiplier}")
	int threadsAllowedToBlockForConnectionMultiplier;
	
	@Value("${mongo.connectTimeout}")
	int connectTimeout;
	
	@Value("${mongo.maxWaitTime}")
	int maxWaitTime;
	
	@Value("${mongo.autoConnectRetry}")
	boolean autoConnectRetry;
	
	@Value("${mongo.socketKeepAlive}")
	boolean socketKeepAlive;
	
	@Value("${mongo.socketTimeout}")
	int socketTimeout;
	
	@Value("${mongo.slaveOk}")
	boolean slaveOk;
	
	@Value("${mongo.databaseName}")
	String databaseName;
	
	@Override
	public @Bean MongoTemplate mongoTemplate() throws Exception {  
        return new MongoTemplate(mongo(),databaseName);  
    }  
	
	/**                                                          
	* 描述 : <负责解析资源文件>. <br> 
	*<p> 
		<这个类必须有，而且必须声明为static，否则不能正常解析>  
	 </p>                                                                                                                                                                                                                                                
	* @return                                                                                                      
	*/  
    public static @Bean PropertySourcesPlaceholderConfigurer placehodlerConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
	
	@Override
	public @Bean Mongo mongo() throws Exception {
		MongoClientOptions options =  new MongoClientOptions.Builder().socketKeepAlive(socketKeepAlive)
				.connectTimeout(connectTimeout)
				.socketTimeout(socketTimeout)
				.maxWaitTime(maxWaitTime)
				.threadsAllowedToBlockForConnectionMultiplier(threadsAllowedToBlockForConnectionMultiplier)
				.writeConcern(WriteConcern.NORMAL).build();
		
		MongoClient client = new MongoClient(new ServerAddress(host, port), options);
		return client;
	}

	@Override
	protected String getDatabaseName() {
		return databaseName;
	}
	
}
